package itsm.isperp.module.controller.wechat;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.DateUtils;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.module.dto.app.ChatMessage;
import itsm.isperp.module.entity.wechat.WechatChat;
import itsm.isperp.module.service.wechat.WechatChatService;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpCustomMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-5-29
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("wechat/chat")
public class WechatChatController extends BaseController<WechatChat> {

	@Autowired
	protected WechatChatService wechatChatService;

	@Autowired
	SimpMessagingTemplate simpMessagingTemplate;

	@Override
	public WechatChatService getService() {
		return wechatChatService;
	}

	@Override
	public String getPageTitle() {
		return "聊天";
	}

	@RequestMapping("chatView")
	public String chat(Model model) {

		String name = ContextHolder.getLoginUser().getFullname();

		List<Map<String, Object>> chattings = this.getService()
				.findAllGroupByOpenid();
		model.addAttribute("name", name);
		model.addAttribute("chattings", chattings);

		return "wechat/chat/chatView";
	}

	@RequestMapping("listChats")
	@ResponseBody
	public List<WechatChat> listChats(String openid) {
		List<WechatChat> list = this.getService().listChats(openid);
		return list;
	}

	// 发送消息指到的openid
	@MessageMapping("/send")
	public void send(ChatMessage message) {

		WechatChat c = new WechatChat();
		c.setOpenid(message.getOpenid());
		c.setSendContent(message.getData());
		c.setMsgType(message.getMsgType());
		c.setSenderName(message.getSenderName());
		c.setSendFrom(message.getSender());
		c.setSendTime(new Timestamp(new Date().getTime()));
		wechatChatService.saveOrUpdate(c);
		message.setSendTime(DateUtils.formatDateTime(c.getSendTime()));

		WxMpCustomMessage m = new WxMpCustomMessage();
		m.setContent(message.getData());
		m.setMsgType(me.chanjar.weixin.common.api.WxConsts.CUSTOM_MSG_TEXT);
		m.setToUser(message.getOpenid());

		WxMpService wxMpService = ContextHolder.getSpringBean("wxMpService");
		try {
			wxMpService.customMessageSend(m);
		} catch (WxErrorException e) {
			m.setContent(e.toString());
		}

		// 广播消息
		simpMessagingTemplate.convertAndSend("/chatMessage/result", message);

	}
}
